import React, { useRef, useEffect } from 'react';
import gsap from 'gsap';
import './NavTabs.css';

export interface TabItem {
  id: string;
  label: string;
  disabled?: boolean;
}

interface NavTabsProps {
  items: TabItem[];
  activeTab: string;
  onTabChange: (tabId: string) => void;
  className?: string;
  variant?: 'default' | 'underline' | 'pills';
  size?: 'small' | 'medium' | 'large';
}

const NavTabs: React.FC<NavTabsProps> = ({
  items,
  activeTab,
  onTabChange,
  className = '',
  variant = 'underline',
  size = 'medium'
}) => {
  const tabsRef = useRef<HTMLDivElement>(null);
  const indicatorRef = useRef<HTMLDivElement>(null);
  const tabRefs = useRef<(HTMLDivElement | null)[]>([]);

  const handleTabClick = (tabId: string, disabled?: boolean) => {
    if (disabled) return;
    onTabChange(tabId);
  };

  // 更新滑动指示器位置
  const updateIndicatorPosition = () => {
    const activeIndex = items.findIndex(item => item.id === activeTab);
    if (activeIndex === -1 || !indicatorRef.current || !tabRefs.current[activeIndex]) return;

    const activeTabElement = tabRefs.current[activeIndex];
    const tabsContainer = tabsRef.current;
    
    if (!activeTabElement || !tabsContainer) return;

    const tabRect = activeTabElement.getBoundingClientRect();
    const containerRect = tabsContainer.getBoundingClientRect();
    
    const left = tabRect.left - containerRect.left;
    const width = tabRect.width;

    gsap.to(indicatorRef.current, {
      left: left,
      width: width,
      duration: 0.3,
      ease: "power2.out"
    });
  };

  // 当activeTab变化时更新指示器位置
  useEffect(() => {
    updateIndicatorPosition();
  }, [activeTab, items]);

  // 当组件挂载时设置初始位置
  useEffect(() => {
    updateIndicatorPosition();
  }, []);

  return (
    <div style={{position: 'relative'}}>
    <div ref={tabsRef} className={`nav-tabs ${variant} ${size} ${className}`}>
      {/* 滑动指示器 */}
      {variant === 'pills' && (
        <div ref={indicatorRef} className="nav-tab-indicator" />
      )}
      
      {items.map((item, index) => (
        <div
          key={item.id}
          ref={(el) => {
            tabRefs.current[index] = el;
          }}
          className={`nav-tab ${activeTab === item.id ? 'active' : ''} ${
            item.disabled ? 'disabled' : ''
          }`}
          onClick={() => handleTabClick(item.id, item.disabled)}
        >
          {item.label}
        </div>
      ))}
    </div>
    </div>
  );
};

export default NavTabs;
